package yf.mall.controller.api;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.service.WxWebService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import yf.mall.common.Const;
import yf.mall.dao.AccountDao;
import yf.mall.dao.AreaDao;
import yf.mall.dao.LevelDao;
import yf.mall.dao.TeamSaleDao;
import yf.mall.entity.*;
import com.yf.response.R;
import yf.mall.enums.*;
import yf.mall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import yf.mall.vo.MallOrderVo;
import yf.mall.vo.ShopVo;
import yf.mall.vo.UserEntityVo;
import yf.mall.vo.UserVo;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.AbstractList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/api/user")
@RestController
public class ApiUserController {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ShopService shopService;

    @GetMapping("/team/{code}")
    @IgnoreAuth
    public R team(@PathVariable String code, Integer type){
        UserEntity userEntity = userService.findByCode(code);
         List<UserVo> userVos = userService.findByTop(userEntity.getId(),type);
         List<Long> userIds = userVos.stream().map(userVo -> userVo.getUser().getId()).collect(Collectors.toList());
        return R.ok(userIds);
    }

    /**
     * TODO 接入Redis存储验证码，接入短信发送验证码
     * 生成验证码,发送
     *
     * @param mobile
     * @return
     */
    @RequestMapping("/captcha")
    @IgnoreAuth
    public R captcha(String mobile) {
        String captcha = noticeService.sendCaptcha(mobile);
//        String captcha = "123456";
        return R.ok(captcha);
    }

    @Autowired
    private WxWebService wxWebService;

    /**
     * 获取公众号二维码
     *
     * @param userId
     * @return
     */
    @RequestMapping("/qr/code")
    public R getQrCode(@LoginUserId Long userId) {
        String url = wxWebService.getQrCodeUrl(String.valueOf(userId));
        return R.ok(url);
    }

    @RequestMapping("/auth/img")
    @IgnoreAuth
    public void authImg(HttpServletResponse response, Long userId) {
        userService.createAuthImg(userId, response);
    }

    /**
     * TODO 绑定以及生成代理编号
     * 绑定手机号码(可以此时发放)
     *
     * @param userId
     * @param mobile
     * @return
     */
    @RequestMapping("/mobile")
    public R mobile(@LoginUserId Long userId, String mobile) {
        return R.ok();
    }


    /**
     * 根据手机号或者编号或者名字或者电话查询
     *
     * @return
     */
    @RequestMapping("/search")
    @IgnoreAuth
    public R search(@LoginUserId Long userId, String param) {
        List<UserVo> userEntities = userService.findByNameOrCodeOrMobile(param);
        return R.ok(userEntities);
    }

    @Autowired
    private AreaDao areaDao;

    /**
     * 查询下级
     * type 0 无限层
     *
     * @return
     */
    @RequestMapping("/top/search")
    public R searchByTop(@LoginUserId Long userId, @RequestParam(name = "type") Integer type) {
        List<UserVo> userEntities = userService.findByTop(userId, type);
//        List<UserEntityVo> userEntities = userService.findByTop(userId, type);
        //获取区域代理  que
        if (userEntities != null && userEntities.size() > 0) {
            for (UserVo userEntity : userEntities) {
                List<AreaEntity> entityList = areaDao.findByUserId(userEntity.getUser().getId());
                UserEntity user = userEntity.getUser();

                if (entityList != null && entityList.size() > 0) {
                    String areaName = entityList.get(0).getName();
                    if (areaName != null && !"".equals(areaName)) {
                        // 省管理
                        if (!areaName.contains("市") && areaName.contains("省")) {
                            user.setAreaName(areaName);
                        }
                        //市管理
                        if (areaName.contains("市") && !areaName.contains("区") && !areaName.contains("县")) {
                            String[] strings = areaName.split("市");
                            //如果出现多个市的情况 则取最后一个
                            if (strings.length > 1) {
                                user.setAreaName(strings[strings.length - 1] + "市");
                            }
                            //只出现一个市的情况
                            if (strings.length > 0 && strings.length < 2) {
                                String str = strings[0];
                                //根据省分割 取得市
                                if (str.contains("省")) {
                                    user.setAreaName(str.split("省")[1] + "市");
                                }
                            }
                        }
                        // 区or县管理
                        if (areaName.contains("区") || areaName.contains("县")) {
                            //根据市分割 取最后一个则是区
                            String[] strs = areaName.split("市");
                            user.setAreaName(strs[strs.length - 1]);
                        }
                    }

                }
            }
        }
        UserEntity user = userService.get(userId);
        UserEntity topUser = userService.get(user.getPid());
        LevelEntity levelEntity = levelService.get(user.getLevelId());
        UserEntity adminUser = null;
        if (levelEntity.getName().contains("联盟单位")){
            adminUser = userService.get(Const.ADMIN_ID);
        }
        return R.ok(userEntities).putExtra("topUser", topUser).putExtra("user", user).putExtra("adminUser",adminUser);
    }

    @RequestMapping("/update")
    public R update(@LoginUserId Long userId, String phone, String password, String name, Boolean sync,String topPhone) {
        UserEntity userEntity = userService.update(userId, phone, password, name, sync,topPhone);
        return R.ok(userEntity);
    }



    @Autowired
    private MyService myService;
    @Autowired
    private MallOrderService mallOrderService;

    @Autowired
    private CouponService couponService;

    /**
     * 查找用户信息
     * TODO 限制只有团队长能看团队下面的
     *
     * @param userId
     * @param uid
     * @return
     */
    @RequestMapping("/info")
    public R info(@LoginUserId Long userId, Long uid) {
        UserEntity userEntity;
        LevelEntity levelEntity = null;
        List<AccountEntity> accountEntities;
        String topCode = "";
        BigDecimal waitIncome = new BigDecimal(0); //代收款
        BigDecimal exp = BigDecimal.ZERO;
        String mobile = "";
        List<CouponEntity> coupons;
        List<CouponEntity> allCoupons;
        //查找别人
        if (uid != null) {
            coupons = couponService.findByUserIdAct(uid);
            allCoupons = couponService.findByUserId(uid);
            UserEntity user = this.userService.get(userId);
            userEntity = userService.get(uid);
            Long pid = user.getPid();
            levelEntity = levelService.get(userEntity.getLevelId());
            if (pid.equals(uid)) {
                levelEntity.setName("**");
            }
            accountEntities = accountService.findByUserId(uid);
        } else {//查找自己
            coupons = couponService.findByUserIdAct(userId);
            allCoupons = couponService.findByUserId(userId);
            // 查找距离跟上一级别的经验值之差
            exp = this.myService.findTopLv(userId);
            userEntity = userService.get(userId);
            levelEntity = levelService.get(userEntity.getLevelId());
            accountEntities = accountService.findByUserId(userId);
            UserEntity topUser = userService.get(userEntity.getPid());
            topCode = topUser.getCode();
            mobile = topUser.getMobile();
            waitIncome = accountRecordService.waitIncome(userId);
        }
        List<UserEntity> vipUsers = userService.findByVip(userEntity.getTCode());
        BigDecimal sumSale = teamSaleDao.sumTotalPrice(userId,new Date());
        return R.ok(userEntity).putExtra("level", levelEntity).putExtra("coupons",coupons).putExtra("allCoupons",allCoupons).putExtra("accounts", accountEntities)
                .putExtra("topCode", topCode).putExtra("sumSale",sumSale).putExtra("waitIncome", waitIncome).putExtra("exp", exp).putExtra("mobile",mobile).putExtra("vipUsers",vipUsers);
    }

    @Autowired
    private TeamSaleDao teamSaleDao;

    @RequestMapping("shopInfo")
    public R shopInfo(@LoginUserId long userId) {
        Map<String, Object> map = mallOrderService.shopOrderInfo(userId);
        Integer totalOrderNum = (Integer) map.get("totalOrderNum"); //店铺总订单数
        BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");//店铺总金额
        BigDecimal nowPrice = (BigDecimal) map.get("todayPrice"); //店铺今日订单金额
        Integer nowOrderNum = (Integer) map.get("todayOrderNum"); //店铺今日订单数

        Map<String, BigDecimal> mapIncome = accountRecordService.findByToUserId(userId, AccountRecordTypeEnum.CASH.getIndex(), AccountRecordBusEnum.SHOP.getIndex(), AccountRecordStatusEnum.DONE.getIndex());
        BigDecimal downIncome = mapIncome.get("downIncome");  //店铺已收款金额
        BigDecimal totalIncome = mapIncome.get("totalIncome");  //店铺实际总收入
        ShopEntity shop = shopService.findByUserId(userId);
        return R.ok().putExtra("shop", shop)
                .putExtra("nowPrice", nowPrice).putExtra("nowOrderNum", nowOrderNum).putExtra("totalPrice", totalPrice).putExtra("totalOrderNum", totalOrderNum)
                .putExtra("totalIncome", totalIncome).putExtra("downIncome", downIncome);
    }

    @RequestMapping("/nowUserInfo")
    public R nowUserInfo(@LoginUserId Long userId) {
        UserEntityVo userEntityVo = this.userService.findNowUserInfo(userId);

        return R.ok(userEntityVo);
    }

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private LevelDao levelDao;

    @RequestMapping("/levels")
    public R Level() {
        List<LevelEntity> levelEntities = levelService.findlist();
        return R.ok(levelEntities);
    }

    @RequestMapping("/level")
    public R levels(@LoginUserId Long userId) {
        List<LevelEntity> levelEntities = levelService.findLowLevel(userId);
        return R.ok(levelEntities);
    }

    @RequestMapping("/level/change")
    public R changeLevel(@LoginUserId Long userId, Long toUserId, Long levelId) {
        LevelEntity levelEntity = levelService.changeLevel(userId, toUserId, levelId);
        return R.ok(levelEntity);
    }




    @Autowired
    private UserService userService;

    @Autowired
    private LevelService levelService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountRecordService accountRecordService;

}
